package com.dragon.controller;

import com.dragon.pojo.*;
import com.dragon.pojo.enums.SupportLanguageEnum;
import com.dragon.service.SandboxService;
import com.dragon.service.impl.SandboxDispatchService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.File;
import java.util.List;

@Slf4j
@RequestMapping("/sandbox")
@RestController
public class JudgeController {
    @Autowired
    SandboxDispatchService sandboxServiceMap;

    @GetMapping("/healthCheck")
    public String healthCheck(){
        return "I'm fine";
    }

    @PostMapping("/run")
    public ExecuteCodeResponse run(@RequestBody CodePayload codePayload){
        // 根据语言选择出相关 service
        SandboxService sandboxService = sandboxServiceMap.getSandboxServiceMap().get(codePayload.getLanguage());
        if(sandboxService == null){
            return ExecuteCodeResponse.error("不支持当前语言:" + codePayload.getLanguage() + "，当前仅支持:" + SupportLanguageEnum.getValues(),0, codePayload.getCode());
        }
        File codeFile = null;
        try {
            log.info("代码语言:{}",codePayload.getLanguage());
            // 保存用户代码
            codeFile = sandboxService.saveCodeToFile(codePayload.getCode());
            // 编译代码
            ExecuteMessage compileMessage = sandboxService.compileFile(codeFile);
            // 获取编译结果
            boolean compileResult = compileMessage.getExitValue() == 1;
            if(!compileResult){
                // 运行代码
                List<ExecuteMessage> runMessagesList = sandboxService.runFile(codeFile, codePayload.getInputList(),codePayload.getTimeLimit());
                // 获取响应结果
                ExecuteCodeResponse outputResponse = sandboxService.getOutputResponse(runMessagesList, codePayload, codeFile);
                // 获取文件大小
                sandboxService.getFileSize(codeFile);
                // 删除文件
                sandboxService.deleteFile(codeFile);
                return outputResponse;
            } else {
                return ExecuteCodeResponse.compileError("Compile Error", compileMessage.getErrorMessage(), codePayload.getCode());
            }
        } catch (Exception e) {
            log.error(String.valueOf(e));
            // 运行异常依然删除目录
            sandboxService.deleteFile(codeFile);
//            throw new RuntimeException(e);
            return ExecuteCodeResponse.error(String.valueOf(e));
        }

    }

    @PostMapping("test")
    public TestRunResponse TestRun(@RequestBody TestPayload testPayload) {
        // 根据语言选择出相关 service
        SandboxService sandboxService = sandboxServiceMap.getSandboxServiceMap().get(testPayload.getLanguage());
        if(sandboxService == null){
            return TestRunResponse.error("不支持当前语言:" + testPayload.getLanguage() + "，当前仅支持:" + SupportLanguageEnum.getValues());
        }
        File codeFile = null;
        try {
            log.info("代码语言:{}",testPayload.getLanguage());
            // 保存用户代码
            codeFile = sandboxService.saveCodeToFile(testPayload.getCode());
            // 编译代码
            ExecuteMessage compileMessage = sandboxService.compileFile(codeFile);
            // 获取编译结果
            boolean compileResult = compileMessage.getExitValue() == 1;
            if(!compileResult){
                // 运行代码
                List<ExecuteMessage> runMessagesList = sandboxService.runFile(codeFile, testPayload.getInput(),5000);
                // 获取运行结果
                String output = runMessagesList.get(0).getMessage();
                // 删除文件
                sandboxService.deleteFile(codeFile);
                return TestRunResponse.success(output);
            } else {
                return TestRunResponse.error("Compile Error");
            }
        } catch (Exception e) {
            log.error(String.valueOf(e));
            // 运行异常依然删除目录
            sandboxService.deleteFile(codeFile);
            throw new RuntimeException(e);
//            return TestRunResponse.error(String.valueOf(e));
        }
    }
}
